package com.heima.model.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 枚举校验注解处理类
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private String[] strValues;
    private short[] shortValues;  //合法的参数数组,我们自定义的是:[0,1]

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        strValues = constraintAnnotation.strValues();
        shortValues = constraintAnnotation.shortValues();  //合法的参数数组,我们自定义的是:[0,1]
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {  //判断我们传入的value值的类型
        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Short) {  //如果输入的value是Integer类型
            for (short s : shortValues) {  //遍历合法的value数组[0,1]
                if (s == (short)value) {  //判断合法的value与我们输入的强转为Short类型的value是否相同
                    return true;
                }
            }
        }
        return false;
    }
}